#pragma once
#include<iostream>
#include<string>
#include<string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include"Common.hpp"

//输入网络协议结构体，转换为本地IP+端口
class InetAddr
{
public:
    InetAddr(sockaddr_in addr):_addr(addr)
    {
        //网络转主机
        //_ip=inet_ntoa(_addr.sin_addr);
        char ipbuffer[64];
        inet_ntop(AF_INET,&addr.sin_addr,ipbuffer,sizeof(ipbuffer));
        _ip=ipbuffer;
        _port=ntohs(_addr.sin_port);
    }

    InetAddr(uint16_t port,const std::string ip): _port(port),_ip(ip)
    {
        //主机转网络
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
        inet_pton(AF_INET,_ip.c_str(),&_addr.sin_addr);
    }

    InetAddr(uint16_t port):_port(port),_ip(INADDR_ANY)
    {
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
        inet_pton(AF_INET,_ip.c_str(),&_addr.sin_addr);
    }

    uint16_t Port()const{return _port;}
    std::string Ip()const{return _ip;}
    const sockaddr_in& Addr()const {return _addr;}

    sockaddr* NetAddrPtr(){ return CONV(_addr);}

    socklen_t NetAddrLen(){return sizeof(_addr);}

    bool operator==(const InetAddr&ia)
    {
        return _ip==ia._ip&&_port==ia._port;
    }

    std::string StringAddr() const
    {
        std::string mg="["+_ip+":"+std::to_string(_port)+"]";
        return mg;
    }
    ~InetAddr()
    {
        
    }
private:
    sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};